package com.assets.Maintain;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Adapter.Maintain_adapter;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.misc.Accompaniment;
import com.assets.uhf.util.DataTransfer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.senter.iot.support.openapi.uhf.UhfD2;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/4/25.
 */

public class Maintain_add extends Activity implements OnDismissListener {
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private boolean state;
    private Button add;
    private ImageView fh;
    private boolean isrfid=true;
    private String deviceId;//设备id
    private String id,name,partId;
    private String url="http://"+ Url.IP+"/api/devicePartMainAdd";
    ArrayList<Map<String,Object>> data;
    private ListView maintain_lv;
    private Button put_bt;//提交
    private String add_url="http://"+ Url.IP+"/api/devicePartAdd";
    private Handler handler = new Handler();
    private TextView category;//设备名称
    private EditText editText;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String rfid,number;
    private List<String> partid = new ArrayList<>();
    private List<Boolean> booleen = new ArrayList<>();
    private boolean stop_rfid =true;
    private Button scan_img;
    private List<String> rfid_data = new ArrayList<>();
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    private Button RFID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maintain_add);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        indata();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                editText.selectAll();
                category.setText("");
                if (editText.getText().toString().equals(number)){
                    category.setText(name);
                    Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                    maintain_lv.setAdapter(maintain_adapter);
                }else Toast.makeText(Maintain_add.this,"请扫描正确的设备",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void indata() {
        scan_img = (Button) findViewById(R.id.scan_img);
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        put_bt = (Button) findViewById(R.id.put_bt);
        put_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (category.getText().toString().equals("")){
                    Toast.makeText(Maintain_add.this,"请先读取设备再试",Toast.LENGTH_SHORT).show();
                    return;
                }

                new AlertView("提示", "是否常规保养", "否",new String[]{"是"}, null, Maintain_add.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int i) {
                        //正常：position=-1,异常 position=0
                        if (i==0){
                            final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(Maintain_add.this).builder()
                                    .setTitle("保养方案")
                                    .setEditText("");
                            myAlertInputDialog.setCanceledOnTouchOutside(false);
                            myAlertInputDialog.setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (myAlertInputDialog.getResult().equals("")){
                                        Toast.makeText(Maintain_add.this,"请写方案后提交",Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    post(myAlertInputDialog.getResult(),"2","0");
                                    finish();
                                    myAlertInputDialog.dismiss();
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    myAlertInputDialog.dismiss();
                                }
                            });
                            myAlertInputDialog.show();
                        }
                        if (i==-1){
                           post("","0","0");

                        }

                    }
                }).setCancelable(true).setOnDismissListener( Maintain_add.this).show();
            }
        });
        add  = (Button) findViewById(R.id.add);
        name = getIntent().getStringExtra("name");
        deviceId = getIntent().getStringExtra("partId");
        maintain_lv = (ListView) findViewById(R.id.maintain_lv);
        category = (TextView) findViewById(R.id.category);
        number = getIntent().getStringExtra("number");
        editText = (EditText) findViewById(R.id.asset_tag);
        rfid = getIntent().getStringExtra("rfid");
        RFID = (Button) findViewById(R.id.check_rfid);
        RFID.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isrfid==true){
                        if (UhfD2.getInstance().init() == true){
                            UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                        }
                        isrfid = false;
                    }

                }catch (Exception E){
                    Toast.makeText(Maintain_add.this,"没有RFID模块",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (stop_rfid){
                    stop_rfid=false;
                    start_read();
                    RFID.setText("停止读取");
                }else {
                    stop_rfid=true;
                    state =false;
                    RFID.setText("开启RFID");
                }

            }
        });
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (category.getText().toString().equals("")){
                    Toast.makeText(Maintain_add.this,"请先读取设备再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(Maintain_add.this).builder()
                        .setTitle("添加关键部位")
                        .setEditText("");
                myAlertInputDialog.setCanceledOnTouchOutside(false);
                myAlertInputDialog.setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (myAlertInputDialog.getResult().equals("")){
                            Toast.makeText(Maintain_add.this,"请输入部位名称",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Add_part(myAlertInputDialog.getResult());
                        myAlertInputDialog.dismiss();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myAlertInputDialog.dismiss();
                    }
                });
                myAlertInputDialog.show();
            }
        });
        String jsonData = getIntent().getStringExtra("data");
        data = new Gson().fromJson(jsonData, new TypeToken<ArrayList<Map<String,Object>>>(){}.getType());
        Log.i("datadata",data.toString());
        for (int i =0;i<data.size();i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("coding_name", data.get(i).get("partName"));
            map.put("maintain_img","");
            booleen.add(true);
            partid.add((String) data.get(i).get("partId"));
            Log.i("datadata", (String) data.get(i).get("partId"));
            list.add(map);
        }

        maintain_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
               if (booleen.get(position)){
                   new AlertView("保养", "是否异常", "否",new String[]{"是"}, null, Maintain_add.this, AlertView.Style.Alert, new OnItemClickListener() {
                       @Override
                       public void onItemClick(Object o, int i) {
                           //正常：position=-1,异常 position=0
                           if (i==0){
                               Map<String, Object> map = new HashMap<String, Object>();
                               map.put("coding_name", list.get(position).get("coding_name"));
                               map.put("maintain_img",R.mipmap.yichang);
                               list.set(position,map);
                               Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                               maintain_lv.setAdapter(maintain_adapter);
                               booleen.set(position,false);
                               partId = partid.get(position);
                               Intent intent = new Intent(Maintain_add.this,Maintain_Scheme.class);
                               intent.putExtra("partid",partId);
                               intent.putExtra("number",number);
                               intent.putExtra("state",position);
                               startActivity(intent);

                               //Toast.makeText(Receive_add.this,"申请添加成功",Toast.LENGTH_SHORT).show();
                                  /*  category_name.setText("");
                                    num.setText("");*/
                           }
                           if (i==-1){

                           }

                       }
                   }).setCancelable(true).setOnDismissListener( Maintain_add.this).show();
               }

            }
        });
    }

    private void Add_part(final String part){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("deviceId",deviceId)
                        .add("part",part);
                final Request request = new Request.Builder()//创建Request 对象。
                        .url(add_url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(Maintain_add.this,"请连接网络后重试",Toast.LENGTH_SHORT).show();
                                Log.i("123123", "error");
                            }
                        });

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("state").equals("1"))
                                    {
                                        Map<String, Object> map = new HashMap<String, Object>();
                                        map.put("coding_name", jsonObject.getString("partName"));
                                        map.put("maintain_img","");
                                        booleen.add(true);
                                        partid.add(jsonObject.getString("partId"));
                                        list.add(map);
                                        Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                                        maintain_lv.setAdapter(maintain_adapter);
                                        Toast.makeText(Maintain_add.this,"添加成功",Toast.LENGTH_SHORT).show();
                                    }
                                    else if (jsonObject.getString("state").equals("0")){
                                        Toast.makeText(Maintain_add.this,"添加失败",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                    }
                });

            }
        }).start();

    }

    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    if (rfid.equals(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                category.setText(name);
                                Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                                maintain_lv.setAdapter(maintain_adapter);
                            }
                        });
                    }
                    trigTagAccompainiment();//播放声音
                }


            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }

    @Override
    public void onDismiss(Object o) {

    }
    public void post(final String remark, final String iserror, final String parid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("userId",id)
                .add("deviceNumber",number)
                .add("partId",parid)
                .add("iserror",iserror)
                .add("remark",remark); //传递键值对参数

                final Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(Maintain_add.this,"请连接网络后重试",Toast.LENGTH_SHORT).show();
                                Log.i("123123", "error");
                            }
                        });

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        Log.i("statestate",responseData);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("state").equals("1"))
                                    {
                                        Toast.makeText(Maintain_add.this,"提交成功",Toast.LENGTH_SHORT).show();
                                        if (iserror.equals("0")||iserror.equals("2")){
                                            finish();
                                        }
                                    }
                                    else   if (jsonObject.getString("state").equals("0"))
                                    {
                                        Toast.makeText(Maintain_add.this,"提交失败",Toast.LENGTH_SHORT).show();

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                    }
                });

            }
        }).start();

    }


    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Maintain_add.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Maintain_add.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Maintain_add.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Maintain_add.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Maintain_add.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Maintain_add.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Maintain_add.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (scanResult.equals(number)){
                category.setText(name);
                Maintain_adapter maintain_adapter = new Maintain_adapter(Maintain_add.this,list);
                maintain_lv.setAdapter(maintain_adapter);
            }else Toast.makeText(Maintain_add.this,"请扫描正确的设备",Toast.LENGTH_SHORT).show();
        }
    }
}
